import React, {useEffect, useState} from 'react'
import { Form, Button, Input, Modal, Row, Col, DatePicker, Select, message, Upload, Switch } from 'antd'
import { connect } from 'umi'
import {UploadOutlined} from '@ant-design/icons';
import {getContractSubjectList} from "@/pages/Contract/service";
import {getUploadUrl} from "@/utils/upload";
import moment from 'moment'

const FormItem = Form.Item;
const {Option} = Select;
const {RangePicker} = DatePicker;

const formLayout = {
  labelCol: { span: 7 },
};

const colStyle = {
  xl: 12,
  lg: 12,
  md: 12,
  sm: 12,
  xs: 12,
};

let uploadedFiles = [];

const CreateForm = (props) => {

  const { onSubmit, onCancel, visible, current, currentUser = {} } = props;
  const [form] = Form.useForm();
  const [contractData,setContractData] = useState([]);
  const [fileName, setFileName] = useState(null);
  const [fileUploadUrls, setFileUploadUrls] = useState([]);
  const [fileList, setFileList] = useState([]);

  const fileProps = {
    name: 'file',
    multiple: false,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    fileList: fileList,
    beforeUpload(file) {
      if (file.size/1024 > 10000) {
        message.error(`上传文件大小不能超过10M！`);
        return false;
      }
      setFileName(file.name)
    },
    onChange(info) {
      const {status} = info.file;
      if (status === 'done') {
        if (info.file.response.error) {
          message.success(`${info.file.response.error} 。`);
        } else {
          let urls = fileUploadUrls;
          urls.push(info.file.response);
          setFileUploadUrls(urls);
          message.success(`${info.file.name} 文件上传成功。`);
        }
      } else if (status === 'error') {
        message.error(`${info.file.name} 文件上传失败。`);
      }
      let files = info.fileList.filter(item => item.status);
      setFileList(files);
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  useEffect(() => {
    if (visible){
      current || form.setFieldsValue({operateName: currentUser.name});
      getContractSubjectList().then(res => {
        setContractData(res)
      });
      if (current){
        let date = [moment(current.startDate),moment(current.endDate)];
        form.setFieldsValue({ date, ...current });
        if (current.fileUrl){
          let fileUrlList = current.fileUrl.split(',');
          setFileUploadUrls(fileUrlList);
          fileUrlList.forEach((item,index) =>{
            uploadedFiles.push({
              uid: index,
              name: item.split('----')[1],
              status: 'done',
              url: item,
            })
          })
        }
      }
    }
  }, [visible]);

  const selectOnChange = (value, option) => {
    form.setFieldsValue({companyName: option.lable.name});
  };

  const onFormCancel = () => {
    setFileUploadUrls([]);
    uploadedFiles = [];
    form.resetFields();
    onCancel()
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    onSubmit({...fieldsValue, fileUrl: fileUploadUrls.toString()});
    form.resetFields();
    setFileUploadUrls([]);
    uploadedFiles = [];
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col span={0}>
            <FormItem name="id" label="责任险ID">
              <Input type={"text"} />
            </FormItem>
            <FormItem name="companyName" label="被保险单位名称">
              <Input type={"text"} />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="operateName" label="操作人">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="companyId" label="被保险单位" rules={[{required: true, message: '被保险单位不能为空'}]}>
              <Select placeholder="请选择参保单位" showSearch allowClear onChange={selectOnChange}
                      filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} >
                { contractData.length>0 ? contractData.map((item, index) => {
                  return (
                    <Option value={item.id} key={index} lable={item}>
                      {item.name}
                    </Option>
                  )
                }) : ''}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="insuranceUnit" label="承保单位" rules={[{required: true, message: '承保单位不能为空'}]}>
              <Input type={"text"} />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="date" label="保险起止时间" rules={[{required: true, message: '保险起止时间不能为空'}]}>
              <RangePicker className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="money" label="单价" rules={[{required: true, message: '单价不能为空'}]}>
              <Input type="number" />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="maxNumber" label="投保人数" rules={[{required: true, message: '投保人数不能为空'}]}>
              <Input type="number" />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem label="附件上传" labelCol={{span:7}} wrapperCol={{span:17}}>
                <Upload {...fileProps}>
                  <Button>
                    <UploadOutlined/> 点击上传附件
                  </Button>
                </Upload>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" onClick={() => handleSubmit()}>确认</Button>
      </>
    )
  }

  return (
    <Modal
      width={1000}
      destroyOnClose
      title="方案配置"
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}


export default connect(({ user, global }) => ({
  global,
  currentUser: user.currentUser,
}))(CreateForm)
